//
//  GYShoppingCartView.m
//  GoodLuck
//
//  Created by apple on 2018/3/15.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYShoppingCartView.h"
#import "GYBottomTool.h"
#import "GYNetWorkTools.h"
#import "GYUser.h"
#import "AppDelegate.h"

@interface GYShoppingCartView ()<UIGestureRecognizerDelegate,UITextFieldDelegate,GYBottomToolDeleagte,CAAnimationDelegate>
@property (weak, nonatomic) IBOutlet UIView *shoppingView;
@property (weak, nonatomic) IBOutlet UITextField *goodsNumTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *deleteBtu;
@property (weak, nonatomic) IBOutlet UIButton *addBtu;

@property (weak, nonatomic) IBOutlet UIImageView *goodImageView;
@property (weak, nonatomic) IBOutlet UILabel *goodsNamelable;
@property (weak, nonatomic) IBOutlet UILabel *goodsPriceLable;
@property (weak, nonatomic) IBOutlet UILabel *goodsStockLable;


/** 商品数量 */
@property (nonatomic, assign) NSInteger goodsCount;
@property (weak, nonatomic) IBOutlet UIButton *hiddenBtu;

/** 底部工具栏 */
@property (nonatomic, strong) GYBottomTool *bottomView;

/** 动画的图片 */
@property (nonatomic, weak) UIImageView *animationImageView;

/** 该商品的ID */
@property (nonatomic, strong) NSString *goods_id;

/** 商品库存 */
@property (nonatomic, assign) NSInteger goods_collect;
@end
@implementation GYShoppingCartView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.goodsCount = 1;
    self.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.6];
    self.goodsNumTextFiled.text  = [NSString stringWithFormat:@"%zd",self.goodsCount];
    self.deleteBtu.enabled = self.goodsCount == 1 ? NO : YES;
    self.hiddenBtu.layer.cornerRadius = 10;
    //1.创建键盘辅助视图
    UIView * accessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    accessoryView.backgroundColor = RGBColor(245, 245, 245);
    UIButton *btu = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-50, 0, 50, 30)];
    [btu setTitle:@"完成" forState:UIControlStateNormal];
    [btu setTitleColor:RGBColor(252, 139, 43) forState:UIControlStateNormal];
    [btu addTarget:self action:@selector(changedGoodsNum) forControlEvents:UIControlEventTouchUpInside];
    [accessoryView addSubview:btu];
    self.goodsNumTextFiled.inputAccessoryView = accessoryView;
    
    //2.创建底部工具栏
    GYBottomTool *bottomView = [[GYBottomTool alloc] initWithFrame:CGRectMake(0, self.shoppingView.height-55, ScreenWidth, 55)];
    bottomView.delegate = self;
    [self.shoppingView addSubview:bottomView];
    self.bottomView = bottomView;
}

- (void)setGoodsDtailsDic:(NSDictionary *)goodsDtailsDic {
    _goodsDtailsDic = goodsDtailsDic;
    
    NSDictionary *goods_info = [goodsDtailsDic objectForKey:@"goods_info"];
    NSArray *spec_image = [goodsDtailsDic objectForKey:@"spec_image"];
    [self.goodImageView sd_setImageWithURL:[NSURL URLWithString:[spec_image firstObject]] placeholderImage:[UIImage imageNamed:@"4"]];
    self.goodsNamelable.text = [goods_info objectForKey:@"goods_name"];
    self.goodsPriceLable.text = [NSString stringWithFormat:@"¥ %@",[goods_info objectForKey:@"goods_price"]];
    self.goods_id = [goods_info objectForKey:@"goods_id"];
    //还有设置库存
    self.goodsStockLable.text = [NSString stringWithFormat:@"库存: %@",[goods_info objectForKey:@"goods_storage"]];
    self.goods_collect = [[goods_info objectForKey:@"goods_storage"] integerValue];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.bottomView.frame = CGRectMake(0, self.shoppingView.height-55, ScreenWidth, 55);
}

- (void)changedGoodsNum {
    [self.goodsNumTextFiled resignFirstResponder];
    self.goodsCount = [self.goodsNumTextFiled.text intValue];
}

- (IBAction)onClick:(UIButton *)sender {
    [self endEditing:NO];
    switch (sender.tag) {
        case 1:
        {
            sender.enabled = self.goodsCount == 1 ? NO : YES;
            if (self.goodsCount > 1) {
                self.goodsCount -= 1;
                self.goodsNumTextFiled.text = [NSString stringWithFormat:@"%zd",self.goodsCount];
            }
        }
            break;
            
        case 2:
        {
            //这里应该还要判断不能超过最大库存
            if (self.goodsCount == self.goods_collect) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"购买数量不能超过库存量!" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }else {
                self.goodsCount += 1;
            }
            self.goodsNumTextFiled.text = [NSString stringWithFormat:@"%zd",self.goodsCount];
            self.deleteBtu.enabled = self.goodsCount == 1 ? NO : YES;
        }
            break;
            
        case 3:
        {
            [self setHidden:YES];
        }
            break;
            
        default:
            break;
    }
    
    //发送一个选择商品数量变化的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateSelectedGoodsNum" object:@(self.goodsCount)];
}


- (IBAction)tapGR:(UITapGestureRecognizer *)sender {
    [self endEditing:NO];
    [self setHidden:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isDescendantOfView:self.shoppingView]) {
        return NO;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([textField.text intValue] < 1) {
        self.goodsCount = 1;
        textField.text = @"1";
    }else {
        if ([textField.text integerValue] > self.goods_collect) {
            self.goodsCount = self.goods_collect;
        }else {
            self.goodsCount = [textField.text integerValue];
        }
        textField.text = [NSString stringWithFormat:@"%zd",self.goodsCount];
    }
    
    //这里要通知选择商品数量发生变化
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateSelectedGoodsNum" object:@(self.goodsCount)];
}


#pragma mark -- GYBottomToolDeleagte

- (void)onButtonClick:(NSInteger)tag {
    //1.判断网络是够正常
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (app.isNetWork) {
        if (tag == 5) {
            //然后执行添加购物车的操作
            //#warning  采用测试的固定的商品ID  需要修改成活动的商品ID @"100670"
            if ([GYUser loadUserInfo] != nil) {
                if (self.goods_collect != 0) {
                    [GYNetWorkTools requestShopingCartAddGoods:self.goods_id quantity:[NSString stringWithFormat:@"%zd",self.goodsCount] success:^(NSDictionary *obj) {
                        
                        int code = [[obj objectForKey:@"code"] intValue];
                        if (code == 200) {
                            NSLog(@"添加商品到购物车 成功....");
                            [[NSNotificationCenter defaultCenter]postNotificationName:updateShopingCartGoodsNum object:nil];
                            if (self.animationImageView == nil) {
                                [self addShopingCartAnimation];
                            }
                        }else if (code == 400) {
                            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[[obj objectForKey:@"datas"] objectForKey:@"error"] message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alertView show];
                            NSLog(@"=======%@",[[obj objectForKey:@"datas"] objectForKey:@"error"]);
                        }
                    } error:^(NSError *error) {
                        NSLog(@"ShopingCartAddGoodsFailed====%@",error);
                    }];
                }else {
                    [EasyTextView showText:@"该商品没有库存,无法加入购物车!"];
                }
            }else {
                [EasyTextView showText:@"请先登陆!"];
            }
        }else if (tag == 4) {
            if (self.goods_collect != 0) {
                self.goodsBuyprocessCallBack(tag,self.goodsCount);
            }else {
                [EasyTextView showText:@"该商品没有库存,无法购买!"];
                [self setHidden:YES];
            }
        }else {
            self.goodsBuyprocessCallBack(tag,self.goodsCount);
        }
    }else {
        [EasyTextView showText:@"亲，您的手机网络不太顺畅喔..."];
    }
}

#pragma mark -- 购物车动画

- (void)addShopingCartAnimation {
    //1.创建一个图片对象
    UIImageView *animationImageView = [[UIImageView alloc] initWithFrame:self.goodImageView.frame];
    animationImageView.image = self.goodImageView.image;
    [self.shoppingView addSubview:animationImageView];
    self.animationImageView = animationImageView;
    
    //给图片添加动画
    
    //1.路线动画
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animation];
    keyAnimation.keyPath = @"position";
    keyAnimation.duration = 1.5;
    keyAnimation.delegate = self;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:animationImageView.center];
    [path addQuadCurveToPoint:CGPointMake(self.bottomView.center.x-(ScreenWidth/6), self.bottomView.center.y) controlPoint:CGPointMake(animationImageView.center.x+80, animationImageView.center.y-50)];
    keyAnimation.path = path.CGPath;
    
    //2.缩放动画
    CABasicAnimation *baseAnimation = [CABasicAnimation animation];
    baseAnimation.keyPath = @"transform.scale";
    baseAnimation.delegate = self;
    baseAnimation.duration = 1.5;
    baseAnimation.toValue = @0.4;
    
    [animationImageView.layer addAnimation:keyAnimation forKey:nil];
    [animationImageView.layer addAnimation:baseAnimation forKey:nil];
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    [self.animationImageView removeFromSuperview];
    self.animationImageView = nil;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.shoppingView endEditing:YES];
}
@end
